#pragma once 

#include<iostream>
#include<unistd.h>
#include<semaphore.h>
#include<vector>
#define NUM 10  //环形队列的容量
class Task{
public:
    int _x,_y;
public:
    Task(int x,int y):_x(x),_y(y)
    {}
    Task(){}

    int run(){
        return _x + _y;
    }
};


template <class T>
class RingQueue{
private:
    std::vector<T> _v;
    int max_capacity;
    //两个信号量
    sem_t sem_data; //标记资源的信号量
    sem_t sem_blank;//标记容量的信号量
    //两个下标索引
    int c_index;
    int p_index;

public:
    RingQueue(int capacity = NUM):max_capacity(capacity),_v(capacity){
        sem_init(&sem_data,0,0);
        sem_init(&sem_blank,0,max_capacity);
        c_index = 0;
        p_index = 0;
    }

    void Get(T& out){
        P(sem_data);
        //消费者获取数据
        out = _v[c_index];
        c_index++;
        c_index %= max_capacity;
        V(sem_blank);
    }
    void Put(const T& in){
        P(sem_blank);
        //生产者生产数据
        _v[p_index] = in;
        p_index++;
        p_index %= max_capacity;
        V(sem_data);
    }
    void P(sem_t& sem){
        sem_wait(&sem);
    }
    void V(sem_t& sem){
        sem_post(&sem);
    }
    ~RingQueue(){
        sem_destroy(&sem_data);
        sem_destroy(&sem_blank);
        c_index = 0;
        p_index = 0;
    }
};
